<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="120px">
      <el-row>
        <el-form-item label="客户姓名" prop="customerName" label-width="80px">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户姓名" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item style="margin-left: 10px;">
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>
      
     
    </el-form>

    <el-row class="row-mbinfo">
    
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="addressList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!--      <el-table-column label="客户地址id" align="center" prop="addressUid" />-->
        <el-table-column label="客户姓名" width="100" align="center" prop="customerName" />        
        <el-table-column label="发票抬头" min-width="120" align="center" prop="companyName"  :show-overflow-tooltip="true"/>
        <el-table-column label="公司税号" min-width="120" align="center" prop="companyNo" />
        <el-table-column label="发票类型" min-width="120" align="center" prop="invoiceTypeStr" />
        <el-table-column label="单位电话" min-width="120" align="center" prop="companyPhone" />    
        <el-table-column label="开户银行" min-width="120" align="center" prop="bankName" />
        <el-table-column label="银行账号" min-width="120" align="center" prop="bankAccountNo" />
        <el-table-column label="邮政编码" min-width="120" align="center" prop="receiverPostCode" />
        <el-table-column label="公司地址" align="center" min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span style="
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            ">
              {{scope.row.companyProvince}}{{scope.row.companyCity}}{{scope.row.companyArea}}{{scope.row.companyAddress}}
            </span>
          </template>
        </el-table-column>	  
	  <el-table-column label="收票人邮箱" min-width="120" align="center" prop="receiverEmail" />
	  <el-table-column label="收票人电话" min-width="120" align="center" prop="receiverPhone" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable>
          <template slot-scope="scope">
            <span>{{scope.row.createTime}}</span>
          </template>
        </el-table-column>

      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改客户收货地址对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- <el-row>
          <el-col :span="24"> -->
            <el-form-item label="客户名称" prop="customerUid" v-if="this.openType=='edit' ">
              <el-input v-model="form.customerUid" disabled style="width: 300px;" />
            </el-form-item>


            
            <el-form-item label="客户名称" prop="customerUid" v-if="this.openType=='add' ">
              <el-select v-model="form.customerUid" filterable placeholder="请选择" style="width: 300px;">
                <el-option v-for="item in customerInfo" :key="item.value" :label="item.customerName"
                  :value="item.customerUid">
                </el-option>
              </el-select>
            </el-form-item>
          <!-- </el-col>
        </el-row>
        <el-row>
          <el-col :span="12"> -->
            <el-form-item label="收货人名称" prop="name">
              <el-input v-model="form.name" maxlength="20" show-word-limit placeholder="请输入收货人姓名" style="width: 300px;" />
            </el-form-item>
          <!-- </el-col>
          <el-col :span="12"> -->
            <el-form-item label="收货人电话" prop="mobile">
              <el-input v-model="form.mobile" maxlength="12" show-word-limit placeholder="请输入收货人联系电话" style="width: 300px;" />
            </el-form-item>
          <!-- </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"> -->
            <el-form-item label="地址">
              <el-cascader ref="cascaderAddr" style="width: 300px;" v-model="form.region" :options="options">
              </el-cascader>
            </el-form-item>
          <!-- </el-col>

        </el-row>

        <el-row>
          <el-col :span="23"> -->
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" type="textarea" :autosize="{ minRows: 2}" maxlength="50"  placeholder="请输入详细地址" style="width: 300px;" />
            </el-form-item>
          <!-- </el-col>
        </el-row>
        <el-row>
          <el-col :span="12"> -->
            <el-form-item label="邮政编号" prop="postCode">
              <el-input v-model="form.postCode" maxlength="6" show-word-limit placeholder="请输入邮政编号" style="width: 300px;" />
            </el-form-item>
          <!-- </el-col>
          <el-col :span="12"> -->
            <el-form-item label="是否默认地址" prop="isDefault">
              <el-select v-model="form.isDefault" placeholder="是否默认地址" style="width: 300px;">
                <el-option v-for="dict in isDefaultOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          <!-- </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看客户收货地址对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>
      <el-form ref="detailForm" label-width="100px">
        <el-row>
          <el-col :span="12" v-for="(item, index) in showData" :key="index" style="margin-top:-15px">
            <el-form-item :label="`${item.label}：`">
              <span>{{ item.value }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handCloseDetail">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listInvoice,
    getAddress,
    delAddress,
    addAddress,
    updateAddress,
    updateAddressStatus
  } from "@/api/customer/address";
  import {
    listInfo
  } from "@/api/customer/Info";
  import {
    getRegion
  } from '@/api/common/regin'
  //验证手机号
  let checkPhone = (rule, value, callback) => {
    let reg =
      /^((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/
    if (!reg.test(value)) {
      callback(new Error('手机号或电话输入错误'))
    } else {
      callback()
    }
  }
  export default {
    name: "Address",
    components: {},

    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 客户收货地址表格数据
        addressList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //查看详细数据
        showData: [],
        //是否默认地址
        isDefaultOptions: [],
        // 地区信息
        options: [],
        // 状态 1有效 0无效字典
        statusOptions: [],
        openType: "",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          customerUid: null,
          name: null,
          mobile: null,
          provinceCode: null,
          provinceName: null,
          cityCode: null,
          cityName: null,
          countyCode: null,
          countyName: null,
          address: null,
          postCode: null,
          isDefault: null,
          createTime: null,
          updateTime: null,
          updateUid: null,
          dataStatus: null,
          customerName: null,
          region: {},
        },
        columns: [{
            label: '数据状态 0无效 1有效 -1删除',
            dataIndex: 'addressUid',
          },
          {
            label: '数据状态 0无效 1有效 -1删除',
            dataIndex: 'customerUid',
          },
          {
            label: '收货人姓名',
            dataIndex: 'name',
          },
          {
            label: '收货人联系电话',
            dataIndex: 'mobile',
          },
          {
            label: '省份代码',
            dataIndex: 'provinceCode',
          },
          {
            label: '省份名称',
            dataIndex: 'provinceName',
          },
          {
            label: '城市代码',
            dataIndex: 'cityCode',
          },
          {
            label: '城市名称',
            dataIndex: 'cityName',
          },
          {
            label: '区县代码',
            dataIndex: 'countyCode',
          },
          {
            label: '区县名称',
            dataIndex: 'countyName',
          },
          {
            label: '详细地址',
            dataIndex: 'address',
          },
          {
            label: '邮政编号',
            dataIndex: 'postCode',
          },
          {
            label: '是否默认地址',
            dataIndex: 'isDefault',
          },
          {
            label: '是否默认地址',
            dataIndex: 'createTime',
          },
          {
            label: '是否默认地址',
            dataIndex: 'updateTime',
          },
          {
            label: '是否默认地址',
            dataIndex: 'updateUid',
          },
          {
            label: '数据状态 0无效 1有效 -1删除',
            dataIndex: 'dataStatus',
          },
        ],

        // 表单参数
        form: {},
        // 表单校验

        rules: {
          isDefault: [{
            required: true,
            message: "是否默认地址不能为空",
            trigger: "blur"
          }],
          mobile: [{
              required: true,
              message: "手机号不能那个为空",
              trigger: "blur"
            },
            {
              type: 'number',
              validator: checkPhone,
              message: '请输入11位有效手机号号码',
              trigger: ['blur', 'change']
            }
          ],
          customerUid: [{
            required: true,
            message: "客户名称不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "收货人姓名不能为空",
            trigger: "blur"
          }]
        },
        //省份数组
        provinceCodeArr: [],
        //城市数组
        cityCodeArr: [],
        //客户信息数组
        customerInfo: []
      };
    },
    created() {
      this.getDicts("customer_is_default").then(response => {
        this.isDefaultOptions = response.data;
      });
      this.getDicts("sys_data_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getList();
      //获取地区信息
      getRegion().then((response) => {
        response.data.forEach(item => {
          let province = new Object();
          province.value = item.value;
          province.label = item.label;
          this.provinceCodeArr.push(province);
          this.options = response.data
        })
      })
    },
    methods: {
      showPhone(row) {
         row.mobileUpdate = row.mobile;
        if (row.mobileStr.indexOf("*") != -1 == false) {
          row.mobileUpdate = row.mobileStr;
          var len = row.mobile.length - 3 - 4;
          var xing = '';
          for (var i = 0; i < len; i++) {
            xing += "*";
          }
          row.mobileStr = row.mobile.substring(0, 3) + xing + row.mobile.substring(row.mobile.length - 4)
        } else {
          row.mobileStr =  row.mobileUpdate;
        }
      },
      //选择城市
      provinceChanage(val) {
        this.queryParams.cityCode = null;
        this.cityCodeArr = [];
        this.options.forEach(item => {
          if (val == item.value) {
            item.children.forEach(childrenItem => {
              let city = new Object();
              city.value = childrenItem.value;
              city.label = childrenItem.label;
              this.cityCodeArr.push(city);
            })
          }
        })
      },
      /** 查询客户收货地址列表 */
      getList() {
        this.loading = true;
        listInvoice(this.queryParams).then(response => {
          this.addressList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          addressUid: null,
          customerUid: null,
          name: null,
          mobile: null,
          provinceCode: null,
          provinceName: null,
          cityCode: null,
          cityName: null,
          countyCode: null,
          countyName: null,
          address: null,
          postCode: null,
          isDefault: null,
          createTime: null,
          updateTime: null,
          updateUid: null,
          dataStatus: "0"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.addressUid)
        this.names = selection.map(item => item.customerName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        //用于禁用删除
        if (this.multiple == false) {
          for (var i = 0; i < selection.length; i++) {
            var element = selection[i];
            if ("1" === element.dataStatus) {
              this.multiple = true;
              break;
            }
          }
        }
        //
        // this.ids = selection.map(item => item.addressUid)
        // this.single = selection.length !== 1
        // this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        //获取地区信息
        getRegion().then((response) => {
          this.options = response.data
        })
        //获取用户信息
        listInfo().then((response) => {
          this.customerInfo = response.rows;
          console.log(this.customerInfo);
        })
        this.reset();
        this.open = true;
        this.openType = "";
        this.openType = "add";
        this.title = "添加客户收货地址";
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        this.viewOpen = true;
        this.viewTitle = "查看客户收货地址";
        this.showData = [];
        this.columns.forEach(item => {
          this.showData.push({
            label: item.label,
            value: row[item.dataIndex]
          })
        })
      },
      handCloseDetail() {
        this.viewOpen = false
        this.showData = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const addressUid = row.addressUid || this.ids
        getAddress(addressUid).then(response => {
          this.form = response.data.customerAddress;
          this.open = true;
          this.openType = "";
          this.openType = "edit";
          this.title = "修改客户收货地址";
          //获取地区信息
          getRegion().then((response) => {
            this.options = response.data
            console.log(this.options);
          })
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          let areaName = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels;
          this.form.countyName = areaName[2];
          this.form.cityName = areaName[1];
          this.form.provinceName = areaName[0];
          let area = this.$refs['cascaderAddr'].getCheckedNodes()[0].path
          this.form.provinceCode = area[0];
          this.form.cityCode = area[1];
          this.form.countyCode = area[2];
          if (valid) {
            if (this.form.addressUid != null) {
              updateAddress(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addAddress(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const addressUids = row.addressUid || this.ids;
        const addressname = row.name;
        this.$confirm('是否确认删除收货人为"' + addressname + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAddress(addressUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.dataStatus === "0" ? "无效" : "有效";
        this.$confirm('确定要把"' + row.customerName + '",设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateAddressStatus(row.addressUid, row.dataStatus);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('customer/address/export', {
          ...this.queryParams
        }, `客户地址.xlsx`)
      }
    }
  };
</script>
